import CalendarUtil from "./calendar";
import moment, { Moment } from "moment";

let format: string = "YYYY-MM-DD";

/**
 * moment 会改变传入的date 对象的 值
 * @param date
 * @param forma
 * @returns
 */
const formatDate = (date: Date, forma: string = format): string => {
  return moment(date).format(forma);
};

/**
 * 农历转公历
 * @param year
 * @param month
 * @param day
 * @returns -1 转换错误
 */
const lunar2solar = (year: number, month: number, day: number): Date => {
  let date: LunarDate | number = CalendarUtil.lunar2solar(year, month, day);
  if (typeof date === "number") {
    throw Error("错误"); //   date===-1
  } else {
    return new Date(date.cYear, date.cMonth - 1, date.cDay);
  }
};

/**
 * 公历转农历
 * @returns -1 转换错误
 */
let solar2lunar = (date: Date) => {
  let val = CalendarUtil.solar2lunar(
    date.getFullYear(),
    date.getMonth() + 1,
    date.getDate()
  );
  if (val == -1) {
    return {
      IMonthCn: "",
      IDayCn: "",
      gzYear: "",
      Animal: "",
      gzMonth: "",
      gzDay: "",
    };
  }
  return val; // as CellDateLunar
};

const isValidDate = (date: Date) => {
  return date instanceof Date && !isNaN(date.getTime());
};

const isWeekend = (date: Date) => {
  return date.getDay() == 6 || date.getDay() == 0;
};

const HolidayJSON = import.meta.glob(`@/components/holiday/*.ts`);

const formatHoliday = (year: number,module: any):Array<HolidayDate> => {
  let holidayResult: Array<HolidayDate> = [];
  if(!module) return holidayResult
  let holidayData = module.default;
  for (const date in holidayData) {
    let res = date.toString();
    if (res && res.length == 4) {
      let month = res.substring(0, 2);
      let day = res.substring(2, 4);
      holidayResult.push({
        date: new Date(year, Number(month) - 1, Number(day)),
        isOnDuty: holidayData[date] == "0",
      });
    }
  }
  return holidayResult;
};

const getHolidayDate = async (year:number) => {
  let data = await readHolidayFile(year);
  return formatHoliday(year,data)
};

const readHolidayFile = async (year: number) => {
  for (const path in HolidayJSON) {
    const result = path.match(/.*\/(.+).ts$/);
    if (result && result[1] === year.toString()) {
      return HolidayJSON[path]()
    }
  }
};

export {
  getHolidayDate,
  isWeekend,
  isValidDate,
  lunar2solar,
  solar2lunar,
  formatDate,
};
